﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using DataAccess;
using DataEntity;
using System.Text;

namespace WebUI.Controllers
{
    public class MenuController : Controller
    {
        //
        // GET: /Menu/
        private DataContext db = new DataContext();
        /// <summary>
        /// 菜单
        /// </summary>
        /// <returns></returns>
        private IEntityRepository<SysMenu> MenuRepository;
        private IEntityRepository<SysUser> UserRepository;
        public MenuController()
        {
            MenuRepository = new EntityRepository<SysMenu>(db);
            UserRepository = new EntityRepository<SysUser>(db);
        }
        public ActionResult Index()
        {
            return View();
        }
        /// <summary>
        /// 菜单列表页面
        /// </summary>
        /// <returns></returns>
        public ActionResult List()
        {
            ViewBag.Create = true;
            ViewBag.Edit = true;
            ViewBag.Delete = true;

            return PartialView();
        }
        /// <summary>
        /// 菜单新建-编辑页面
        /// </summary>
        /// <returns></returns>
        public ActionResult CreateEdit(string type = "Create", int menuid = 0)
        {
            SysMenu menu = new SysMenu();
            if (type == "Create")
            {
                ViewBag.ParentID = menuid;
                var pmenu = MenuRepository.GetByKey(menuid);
                if (pmenu == null)
                {
                    menu.SortNumber = "";
                }
                else
                {
                    menu.SortNumber = pmenu.SortNumber + "99";
                }

            }
            else
            {
                menu = MenuRepository.GetByKey(menuid);
                ViewBag.ParentID = menu.ParentID;
            }
            ViewBag.MenuID = menuid;//当前菜单，create时为0，不影响逻辑
            ViewBag.Type = type;

            return PartialView(menu);
        }
        /// <summary>
        /// 为treegrid提供菜单信息json数据
        /// </summary>
        /// <param name="id"></param>
        /// <returns></returns>
        [HttpPost]
        public ActionResult MenuJson(int id = 0)
        {
            var MenuInfo = (from a in MenuRepository.Get(m => m.ParentID == id)
                            join b in UserRepository.Get() on a.CreateUserName equals b.UserName into ab
                            from CreateUser in ab.DefaultIfEmpty()
                            join c in UserRepository.Get() on a.LastModifyUserName equals c.UserName into ac
                            from LastModifyUser in ac.DefaultIfEmpty()
                            select new
                            {
                                Menu = a,
                                CreateUser,
                                LastModifyUser
                            }).ToList();

            var rootNode = MenuInfo.OrderBy(s => s.Menu.SortNumber).Select(s => new { s.Menu.ID, s.Menu.Name, s.Menu.ParentID, s.Menu.MenuUrl, s.Menu.SortNumber, iconCls = s.Menu.IconCss, state = HasChildMenuIncludeNotShow(s.Menu.ID) == true ? "closed" : "open", HasChild = HasChildMenuIncludeNotShow(s.Menu.ID), CreateRealName = s.CreateUser == null ? "系统管理员" : s.CreateUser.RealName, s.Menu.CreateDate, LastModifyRealName = s.Menu.LastModifyUserName == null ? "" : (s.LastModifyUser == null ? "" : s.LastModifyUser.RealName) }).ToList();

            return JsonHelper.JsonEx(rootNode);
        }
        /// <summary>
        /// 为combotree提供菜单数据 同步
        /// </summary>
        /// <param name="id"></param>
        /// <returns></returns>
        [HttpPost]
        public ActionResult MenuJsonForComboTree(int id = 0)
        {
            var Menus = MenuRepository.Get(m => m.ParentID == id).OrderBy(m => m.SortNumber).ToList();

            StringBuilder sb = new StringBuilder();
            if (Menus.Count() < 1)
            {
                return Json("");
            }
            sb.Append("[");

            //加上 无，即根目录
            sb.Append("{");
            sb.AppendFormat("\"id\":\"{0}\",", "0");
            sb.AppendFormat("\"text\":\"{0}\",", "无（根目录）");
            sb.AppendFormat("\"iconCls\":\"{0}\",", "icon-root");
            sb.AppendFormat("\"attributes\":{0}", System.Web.Helpers.Json.Encode(new { SortNumber = "" }));
            sb.Append("},");

            foreach (var item in Menus)
            {
                sb.Append("{");
                sb.AppendFormat("\"id\":\"{0}\",", item.ID.ToString());
                sb.AppendFormat("\"text\":\"{0}\",", item.IsShow ? item.Name : item.Name + "（不显示）");
                sb.AppendFormat("\"iconCls\":\"{0}\",", item.IconCss);
                sb.AppendFormat("\"attributes\":{0}", System.Web.Helpers.Json.Encode(new { SortNumber = item.SortNumber }));
                sb.Append(GetChildNodesForJson(item.ID));
                sb.Append("},");
            }
            if (sb.ToString().EndsWith(","))
            {
                sb.Remove(sb.Length - 1, 1);
            }
            sb.Append("]");

            return Content(sb.ToString(), "application/json");
        }
        /// <summary>
        /// 找到子节点 返回Json数据
        /// </summary>
        /// <param name="Menus"></param>
        /// <param name="pValue"></param>
        /// <param name="filterDeptID"></param>
        /// <returns></returns>
        private string GetChildNodesForJson(int pValue, int filterDeptID = 0)
        {
            var Nodes = MenuRepository.Get(w => w.ParentID == pValue && w.ID != filterDeptID).OrderBy(o => o.SortNumber).ToList();
            StringBuilder sb = new StringBuilder();
            if (Nodes.Count() < 1)
            {
                return "";
            }
            sb.Append(",\"children\":[");

            foreach (var item in Nodes)
            {
                int pcv = item.ID;
                sb.Append("{");
                sb.AppendFormat("\"id\":\"{0}\",", item.ID.ToString());
                sb.AppendFormat("\"text\":\"{0}\",", item.IsShow ? item.Name : item.Name + "（不显示）");
                sb.AppendFormat("\"iconCls\":\"{0}\",", item.IconCss);
                sb.AppendFormat("\"attributes\":{0}", System.Web.Helpers.Json.Encode(new { SortNumber = item.SortNumber }));
                sb.Append(GetChildNodesForJson(pcv, filterDeptID).TrimEnd(','));
                sb.Append("},");
            }
            if (sb.ToString().EndsWith(","))
            {
                sb.Remove(sb.Length - 1, 1);
            }
            sb.Append("]");
            return sb.ToString();
        }
        #region 其他

        /// <summary>
        /// 是否有子菜单 包含“不显示的菜单”
        /// </summary>
        /// <param name="id"></param>
        /// <returns></returns>
        public bool HasChildMenuIncludeNotShow(int id)
        {
            return MenuRepository.Get().Any(m => m.ParentID == id);
        }

        #endregion
        /// <summary>
        /// 保存
        /// </summary>
        /// <param name="menumodel"></param>
        /// <returns></returns>
        [HttpPost]
        public ActionResult Save([ModelBinder(typeof(JsonBinder<SysMenu>))]SysMenu menumodel)
        {
            try
            {
                //先保存菜单
                if (menumodel.ID == 0)
                {
                    var lastmenu = MenuRepository.Get().OrderByDescending(s => s.ID).FirstOrDefault();
                    if (lastmenu != null)
                    {
                        menumodel.ID = lastmenu.ID + 1;

                    }
                    else
                    {
                        menumodel.ID = 1;
                    }
                    MenuRepository.Insert(menumodel);

                }
                else
                {
                    var Menu = MenuRepository.GetByKey(menumodel.ID);
                    string tempsortnumber = Menu.SortNumber;
                    Menu.Name = menumodel.Name;
                    Menu.IconCss = menumodel.IconCss;
                    Menu.SortNumber = menumodel.SortNumber;
                    Menu.ParentID = menumodel.ParentID;
                    Menu.IsShow = menumodel.IsShow;
                    Menu.MenuUrl = menumodel.MenuUrl;
                    MenuRepository.Update(Menu);

                }
                return Json(new { success = true });


            }
            catch (Exception e)
            {
                return Json(new { msg = e.Message });

            }


        }
        /// <summary>
        /// 删除
        /// </summary>
        /// <param name="ids"></param>
        /// <returns></returns>
        public ActionResult Remove(string ids)
        {
            try
            {
                List<string> ArrId = ids.Split(',').ToList();
                var Menus = MenuRepository.Get().ToList();
                Menus = Menus.Where(f => ArrId.Contains(f.ID.ToString())).ToList();
                MenuRepository.Delete(Menus);
                return Json(new { success = true });

            }
            catch (Exception e)
            {
                return Json(new { msg = e.Message });
            }

        }

    }
}
